//
//  KSSubmitRefundViewController.swift
//  Supermarket
//
//  Created by liuxm on 2017/9/28.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit
import Photos

/// 提交退款
class KSSubmitRefundViewController: KSBaseViewController,PurchaseChoosePhotoDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,PickerPhotoCompleteDelegate,TextFieldDelegate,ChangeStateDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var submitBtn: UIButton!
    var goodsDataArray: [KSRefunListDataListGoodsModel] = []
    private var imageUrlArray: [String] = []
    var orderNumber: String = ""
    private var photo: [PHAsset] = []
    private var photoImage: [UIImage] = []
    private var camera: [UIImage] = []
    private var imageManager = PHCachingImageManager()
    private var isRefund: String = "1"
    private var refundIntro = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "提交退款"
        
        
        self.submitBtn.setBackgroundImage(KSTools.createImageWithColor(color: KSColor.kColorMainRed), for: UIControlState.normal)
        self.submitBtn.setBackgroundImage(KSTools.createImageWithColor(color: KSColor.kColorButtonHighlight), for: UIControlState.highlighted)
        self.submitBtn.setBackgroundImage(KSTools.createImageWithColor(color: KSColor.kColorButtonDisabled), for: UIControlState.disabled)
        
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.backgroundColor = KSColor.kColorViewBackground
        
        let firstCellNib = UINib(nibName: "KSWhetherRefundTableViewCell", bundle: nil)
        self.tableView.register(firstCellNib, forCellReuseIdentifier: "KSWhetherRefundTableViewCell")
        
        let refundNib = UINib(nibName: "KSSubmitRefundTableViewCell", bundle: nil)
        self.tableView.register(refundNib, forCellReuseIdentifier: "KSSubmitRefundTableViewCell")
        
        let explainNib = UINib(nibName: "KSSubmitRefundExplainTableViewCell", bundle: nil)
        self.tableView.register(explainNib, forCellReuseIdentifier: "KSSubmitRefundExplainTableViewCell")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func choosePhoto() {
        let alertViewController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        let photoAlert = UIAlertAction.init(title: "相册", style: .default) { (UIAlertAction) in
            self.openPhoto()
        }
        let cameraAlert = UIAlertAction.init(title: "相机", style: .default) { (UIAlertAction) in
            self.openCamera()
        }
        let cancelAlert = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alertViewController.addAction(photoAlert)
        alertViewController.addAction(cameraAlert)
        alertViewController.addAction(cancelAlert)
        self.present(alertViewController, animated: true) {}
    }
    
    func deletePhoto(index: NSInteger) {
        if index > photo.count {
            self.camera.remove(at: index - photo.count - 1)
        } else {
            self.photo.remove(at: index - 1)
        }
        tableView.reloadData()
    }
    
    private func openCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.camera
            picker.allowsEditing = true
            self.present(picker, animated: true, completion: {
            })
            
        }
    }
    
    private func openPhoto() {
        let vc = KSPickerPhotoAlbumViewController()
        vc.delegate = self
        vc.selectPhotoArray = self.photo
        vc.maxSelected = 3
        vc.cameraChooseNumber = self.camera.count
        let nav = UINavigationController(rootViewController: vc)
        nav.tabBarController?.tabBar.isHidden = true
        self.present(nav, animated: true, completion: nil)
    }
    
    func pickerPhotoComplete(asset: [PHAsset]) {
        self.photo = asset
        tableView.reloadData()
        self.photoImage.removeAll()
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        picker.dismiss(animated: true) {
        }
        self.camera.append(image)
        tableView.reloadData()
    }
    
    func textfieldcallBack(num: String, money: String,cellSection: NSInteger) {
        let model = goodsDataArray[cellSection]
        model.refund_chooseNum = (Int(num))!
        model.refund_chooseMoney = (Float(money))!
        goodsDataArray.remove(at: cellSection)
        goodsDataArray.insert(model, at: cellSection)
    }
    
    func textViewText(text: String) {
        self.refundIntro = text
    }
    
    func changeState(isOn: Bool) {
        self.isRefund = isOn ? "1" : "0"
    }
    
    private func judgeBtnState() {
        //        if !(self.refundIntro.isEmpty) {
        //            for model in goodsDataArray {
        //                if model.refund_chooseMoney > 0 && model.refund_chooseNum > 0 {
        //
        //                }
        //            }
        //        }
    }
    
    @IBAction func completeEvent(_ sender: UIButton) {
        self.imageUrlArray.removeAll()
        if self.photo.count + camera.count == 0 {
            var goodsInfo: [Any] = []
            for model in goodsDataArray {
                let oneGoodsInfo = ["good_sku_relation_id" : model.good_sku_relation_id,"number" : "1","money" : "1"] as [String : Any]
                goodsInfo.append(oneGoodsInfo)
            }
            let parameters = ["order_number" : orderNumber,"is_shipment" : "0","voucher_images" : imageUrlArray,"good_info" : goodsInfo,"remark" : "12312"] as [String : Any]
            self.request.requestDoRefund(parameters: parameters)
        } else {
            if photo.count > 0 {
                for asset in photo {
                    let options = PHImageRequestOptions()
                    self.imageManager.requestImage(for: asset, targetSize: CGSize.init(width: KSConstants.kScreenWidth/4, height: KSConstants.kScreenWidth/4), contentMode: .aspectFit, options: options) { (image, nfo) in
                        if let imageData = UIImageJPEGRepresentation(self.compressImage(sourceImage: image!, targetWidth: KSConstants.kScreenWidth/4), 0.3) as Data? {
                            let datas = ["Filedata" : imageData]
                            self.request.requestUpload(type: "goods_comment", data: datas)
                        }
                        
                    }
                }
                
            }
            
            if self.camera.count > 0 {
                for image in self.camera {
                    let imageData = UIImageJPEGRepresentation(image, 0.3)
                    let datas = ["Filedata" : imageData]
                    self.request.requestUpload(type: "goods_comment", data: datas)
                }
            }
        }
    }
    
    private func compressImage(sourceImage: UIImage,targetWidth: CGFloat) -> UIImage {
        let imageSize = sourceImage.size
        let width = imageSize.width
        let height = imageSize.height
        let targetHeight = (targetWidth / width) * height
        
        UIGraphicsBeginImageContext(CGSize.init(width: targetWidth, height: targetHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
    
    override func requestSuccess(result: String, apiType: KSApiType) {
        super.requestSuccess(result: result, apiType: apiType)
        if apiType == KSApiType.KSUpload {
            let model = KSUploadModel.deserialize(from: result)
            self.imageUrlArray.append((model?.data?.fullPath)!)
            if imageUrlArray.count == photo.count + camera.count {
                let parameters = ["order_number" : orderNumber,"is_shipment" : "0","voucher_images" : imageUrlArray,"good_info" : [["good_sku_relation_id" : "11","number" : "2","money" : "7"]],"remark" : "12312"] as [String : Any]
                self.request.requestDoRefund(parameters: parameters)
            }
        }
    }
    
    override func requestFaile(code: Int, message: String, apiType: KSApiType) {
        super.requestFaile(code: code, message: message, apiType: apiType)
        
    }
}

extension KSSubmitRefundViewController: UITableViewDelegate, UITableViewDataSource {
    
    // UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2 + goodsDataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    // UITableViewDelegate
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        var height = 170
        if indexPath.section == 0 {
            height = 50
        } else if indexPath.section == 3 {
            height = 247
        }
        return CGFloat(height)
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "KSWhetherRefundTableViewCell", for: indexPath) as! KSWhetherRefundTableViewCell
            cell.delegate = self
            return cell
        } else if indexPath.section == 2 + goodsDataArray.count - 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "KSSubmitRefundExplainTableViewCell", for: indexPath) as! KSSubmitRefundExplainTableViewCell
            cell.delegate = self
            cell.setDataWithModel(photo: photo, camera: camera)
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "KSSubmitRefundTableViewCell", for: indexPath) as! KSSubmitRefundTableViewCell
        cell.delegate = self
        cell.setDataWithModel(model: goodsDataArray[indexPath.section - 1],section: indexPath.section - 1)
        return cell
    }
    
}
